#include <fcntl.h>
#include <signal.h>
#include <unistd.h> 
#include <limits.h> 
#include "utils.h"

int to_sockaddr(const char * path, sockaddr_t *sa)
{
  const char *ptr = strchr(path, ':');
  if (ptr != NULL && ptr - path < PATH_MAX){
    char tmp [PATH_MAX];
    strncpy(tmp, path, ptr - path);
    tmp[ptr - path] = 0;
		if (!ip2addr(tmp, &sa->v0))
      return 0;
    strcpy(tmp, ptr + 1);
    uint16_t port;
		if (sockaddr_family(sa) == AF_INET) {
      if (!str2u16(tmp, &port)) 
        return 0;
			sa->v4.sin_port = htons(port);
    }
    return 1;
	} else 
		return ip2addr(path, &sa->v0);
}

socklen_t sockaddr_len(sockaddr_t *sa)
{
	if (sockaddr_family(sa) == AF_INET)
		return sizeof(struct sockaddr_in);
	else if (sockaddr_family(sa) == AF_UNIX){
		return sizeof(struct sockaddr_un);
	} else 
		return 0;
}

void set_nonblock(int fd)
{
	fcntl (fd, F_SETFL, fcntl (fd, F_GETFL) | O_NONBLOCK);      
}

